import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Scale, Server, Activity, Clock } from "lucide-react";

export default function LoadBalancing() {
  const { data: proxyRules = [] } = useQuery({
    queryKey: ["/api/proxy-rules"],
  });

  const { data: backendServers = [] } = useQuery({
    queryKey: ["/api/backend-servers"],
  });

  const getLoadBalancingBadge = (strategy: string) => {
    const colors = {
      "round-robin": "bg-blue-100 text-blue-800",
      "least-connections": "bg-green-100 text-green-800",
      "ip-hash": "bg-purple-100 text-purple-800",
    };
    
    const labels = {
      "round-robin": "轮询",
      "least-connections": "最少连接",
      "ip-hash": "IP哈希",
    };
    
    return (
      <Badge className={colors[strategy as keyof typeof colors] || "bg-gray-100 text-gray-800"}>
        {labels[strategy as keyof typeof labels] || strategy}
      </Badge>
    );
  };

  const getServersByRule = (ruleId: number) => {
    return backendServers.filter((server: any) => server.proxyRuleId === ruleId);
  };

  const getHealthyServerCount = (ruleId: number) => {
    return getServersByRule(ruleId).filter((server: any) => server.status === 'healthy').length;
  };

  return (
    <div className="flex-1 overflow-hidden">
      {/* Header */}
      <header className="bg-white border-b border-slate-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-semibold text-slate-800">负载均衡</h2>
            <p className="text-slate-600">管理和监控负载均衡策略</p>
          </div>
          <div className="flex items-center space-x-2">
            <Scale className="w-5 h-5 text-slate-500" />
            <span className="text-sm text-slate-600">
              {proxyRules.length} 个负载均衡规则
            </span>
          </div>
        </div>
      </header>

      <div className="p-6 overflow-y-auto h-full space-y-6">
        {/* Load Balancing Overview */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-sm font-medium">活跃规则</p>
                  <p className="text-3xl font-bold text-slate-800 mt-2">
                    {proxyRules.filter((rule: any) => rule.status === 'running').length}
                  </p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Activity className="text-blue-600 text-xl" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-sm font-medium">健康服务器</p>
                  <p className="text-3xl font-bold text-slate-800 mt-2">
                    {backendServers.filter((server: any) => server.status === 'healthy').length}
                  </p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <Server className="text-green-600 text-xl" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-sm font-medium">平均响应时间</p>
                  <p className="text-3xl font-bold text-slate-800 mt-2">
                    {Math.round(
                      backendServers.reduce((sum: number, server: any) => sum + (server.responseTime || 0), 0) / 
                      Math.max(backendServers.length, 1)
                    )}ms
                  </p>
                </div>
                <div className="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                  <Clock className="text-yellow-600 text-xl" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Load Balancing Rules */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg font-semibold text-slate-800">负载均衡规则</CardTitle>
            <p className="text-slate-600 text-sm">当前配置的负载均衡策略和服务器分布</p>
          </CardHeader>
          <CardContent>
            {proxyRules.length === 0 ? (
              <div className="text-center py-12">
                <Scale className="w-12 h-12 text-slate-300 mx-auto mb-4" />
                <p className="text-slate-500">暂无负载均衡规则</p>
                <p className="text-sm text-slate-400 mt-2">请先创建代理规则</p>
              </div>
            ) : (
              <div className="space-y-6">
                {proxyRules.map((rule: any) => {
                  const servers = getServersByRule(rule.id);
                  const healthyCount = getHealthyServerCount(rule.id);
                  
                  return (
                    <div key={rule.id} className="border rounded-lg p-6">
                      <div className="flex items-center justify-between mb-4">
                        <div className="flex items-center space-x-4">
                          <h3 className="text-lg font-semibold text-slate-800">{rule.name}</h3>
                          {getLoadBalancingBadge(rule.loadBalancing)}
                          <Badge 
                            className={
                              rule.status === 'running' 
                                ? "bg-green-100 text-green-800 hover:bg-green-100"
                                : "bg-gray-100 text-gray-800 hover:bg-gray-100"
                            }
                          >
                            {rule.status === 'running' ? '运行中' : '已停止'}
                          </Badge>
                        </div>
                        <div className="text-sm text-slate-600">
                          {rule.type} · {rule.localPort} → {rule.remotePort}
                        </div>
                      </div>

                      {rule.description && (
                        <p className="text-slate-600 text-sm mb-4">{rule.description}</p>
                      )}

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                          <h4 className="font-medium text-slate-700 mb-3">服务器状态</h4>
                          <div className="space-y-2">
                            <div className="flex justify-between text-sm">
                              <span className="text-slate-600">健康服务器</span>
                              <span className="text-slate-800">{healthyCount} / {servers.length}</span>
                            </div>
                            <Progress 
                              value={servers.length > 0 ? (healthyCount / servers.length) * 100 : 0} 
                              className="h-2"
                            />
                          </div>
                        </div>

                        <div>
                          <h4 className="font-medium text-slate-700 mb-3">负载分布</h4>
                          {servers.length === 0 ? (
                            <p className="text-sm text-slate-500">暂无后端服务器</p>
                          ) : (
                            <div className="space-y-2">
                              {servers.map((server: any, index: number) => (
                                <div key={server.id} className="flex items-center justify-between text-sm">
                                  <div className="flex items-center space-x-2">
                                    <div 
                                      className={`w-2 h-2 rounded-full ${
                                        server.status === 'healthy' ? 'bg-green-500' : 
                                        server.status === 'unhealthy' ? 'bg-red-500' : 'bg-gray-500'
                                      }`}
                                    />
                                    <span className="text-slate-600">
                                      {server.host}:{server.port}
                                    </span>
                                  </div>
                                  <div className="flex items-center space-x-2">
                                    <span className="text-slate-500">权重: {server.weight}</span>
                                    {server.responseTime && (
                                      <span className="text-slate-500">{server.responseTime}ms</span>
                                    )}
                                  </div>
                                </div>
                              ))}
                            </div>
                          )}
                        </div>
                      </div>

                      {rule.healthCheck && (
                        <div className="mt-4 p-3 bg-blue-50 rounded-lg">
                          <div className="flex items-center space-x-2">
                            <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                            <span className="text-sm text-blue-800">健康检查已启用</span>
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Load Balancing Strategies Info */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg font-semibold text-slate-800">负载均衡策略说明</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="space-y-2">
                <div className="flex items-center space-x-2">
                  {getLoadBalancingBadge("round-robin")}
                  <span className="font-medium text-slate-700">轮询</span>
                </div>
                <p className="text-sm text-slate-600">
                  按顺序将请求分发给每个后端服务器，适用于服务器性能相近的场景。
                </p>
              </div>

              <div className="space-y-2">
                <div className="flex items-center space-x-2">
                  {getLoadBalancingBadge("least-connections")}
                  <span className="font-medium text-slate-700">最少连接</span>
                </div>
                <p className="text-sm text-slate-600">
                  将请求分发给当前连接数最少的服务器，适用于连接时间差异较大的场景。
                </p>
              </div>

              <div className="space-y-2">
                <div className="flex items-center space-x-2">
                  {getLoadBalancingBadge("ip-hash")}
                  <span className="font-medium text-slate-700">IP哈希</span>
                </div>
                <p className="text-sm text-slate-600">
                  根据客户端IP地址的哈希值选择服务器，确保同一客户端始终访问同一服务器。
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
